<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="企业名称" prop="entName">
        <el-input
          v-model="queryParams.entName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="跟进状态" prop="followStatus">
        <el-select
          v-model="queryParams.followStatus"
          placeholder="请选择跟进状态"
          clearable
          class="!w-260px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ENT_FOLLOW_STATUS)"
            :key="dict.value"
            :value="dict.value"
            :label="dict.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
    </el-form>
    <div class="flex justify-between">
      <div>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

        <el-button :disabled="isAllPool" @click="addPool"
          ><Icon icon="ep:delete" class="mr-5px" /> 放入公海</el-button
        >
        <el-button type="primary" :disabled="isAllEmpty || isLoading" @click="addCall"
          ><Icon icon="ep:phone" class="mr-5px" /> 添加到待拨打</el-button
        >
        <br />
        <div class="mt-18px">
          <el-button>
            <span class="mr-10px text-12px flex items-center" v-if="!entAllCheck">全选:</span>
            <span class="mr-10px text-12px flex items-center" v-else>反选:</span>
            <el-checkbox v-model="entAllCheck" @change="setALL"></el-checkbox>
          </el-button>

          <el-button :disabled="entAllCheck" type="primary" plain @click="changeListOne">
            选择首条
          </el-button>
        </div>
      </div>
    </div>
  </ContentWrap>

  <ContentWrap v-for="(item, index) in list" :key="item.id" v-loading="item.loading">
    <div class="flex items-center justify-between text-14px">
      <div class="flex items-center">
        <el-checkbox v-model="item.checked" @change="setALLNo(index)"></el-checkbox>
        <Icon icon="ep:histogram" color="#0052cc" class="mr-4px ml-4px" />
        <el-link class="mr-10px" @click="onEntNameClick(item)">
          {{ item.entName }}
          <Icon icon="ep:arrow-right" />
        </el-link>
        <el-tag
          v-if="followStatusMap[item.followStatus]"
          size="small"
          :type="followStatusMap[item.followStatus].type"
        >
          {{ followStatusMap[item.followStatus].value }}
        </el-tag>
      </div>
      <div class="flex">
        <el-link type="info" @click="putBackSea(item.id)">
          <Icon icon="ep:delete" size="12" class="mr-4px" />
          <span class="text-12px">放回公海</span></el-link
        >
        <el-divider direction="vertical" />
        <el-link type="info" v-if="!item.expersion" @click="setToggleUp(index, true)">
          <span class="text-12px">展开</span>
          <Icon icon="ep:arrow-down" size="12" class="ml-4px" />
        </el-link>
        <el-link type="info" v-else @click="setToggleUp(index, false)">
          <span class="text-12px">收起</span>
          <Icon icon="ep:arrow-up" size="12" class="ml-4px" />
        </el-link>
      </div>
    </div>
    <div class="mt-20px" :class="item.expersion ? '' : 'disnone'">
      <el-table
        :ref="(el) => getTables(el, index)"
        @select="
          (selections) => {
            handleSelect(selections, index)
          }
        "
        @select-all="
          (selections) => {
            handleSelectAll(selections, index)
          }
        "
        @selection-change="
          (selections) => {
            handleSelectionChange(selections, index)
          }
        "
        highlight-current-row
        :stripe="true"
        :data="item.numberList"
        :show-overflow-tooltip="true"
        border
      >
        <el-table-column :selectable="selectable" type="selection" width="55" />
        <el-table-column
          label="领取时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter2"
          width="140"
        />
        <el-table-column label="号码来源" align="left" width="340" prop="descList">
          <template #default="scope">
            <div class="txt flex justify-left items-center flex-wrap" v-if="scope.row.descList">
              <span
                class="ml-10px"
                v-for="(desc, index) in scope.row.descList.split(',')"
                :key="index"
              >
                <a :href="formatDesc(desc, 2)">{{ formatDesc(desc, 1) }}</a>
              </span></div
            >
            <div v-else>企业公开信息 </div>
          </template>
        </el-table-column>

        <!-- TODO: V3.1 显示号码拨号组件，然后对接点呼工作流程 -->
        <el-table-column label="联系号码" align="left" prop="number" width="220">
          <template #default="scope">
            <div v-if="scope.row.numberType != 3" class="flex items-center">
              <el-tag type="danger" v-if="scope.row.primaryNum" size="small" class="mr-4px"
                >关键</el-tag
              >
              {{ scope.row.number }}
              <el-link :underline="false"
                ><Icon
                  @click="onCall(scope.row, scope.row.number, item)"
                  class="ml-5px"
                  icon="ep:phone"
              /></el-link>
              <AddPending
                :number="scope.row.number"
                :source="'ent'"
                :sourceId="scope.row.entId"
                :sourceName="item.entName"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="跟进状态" align="center" prop="followStatus" width="100">
          <template #default="scope">
            <div>
              <el-tag
                v-if="followStatusMap[scope.row.followStatus]"
                size="small"
                :type="followStatusMap[scope.row.followStatus].type"
              >
                {{ followStatusMap[scope.row.followStatus].value }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="标签" align="left" widht="360" prop="tagList">
          <template #default="scope">
            <EntTag
              style="display: inline-block"
              v-for="tag in scope.row.tagList"
              :key="tag.id"
              :content="tag.content"
              :bgColor="tag.bgColor"
              :textColor="tag.textColor"
            />
          </template>
        </el-table-column>
        <!-- TODO: 在这里插入一个鼠标经过时，显示input框， 焦点离开时，如果input不为空，则创建跟进记录 -->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button link type="primary" @click="openCustomerForm(scope.row)"> 转客户 </el-button>
            <el-button link type="primary" @click="openForm('edit', scope.row, scope.row.id)">
              写备注
            </el-button>
            <el-button
              link
              type="primary"
              @click="openTagForm('update', scope.row.id, scope.row.tagList)"
            >
              编辑标签
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="item.total"
        v-model:page="item.pageNo"
        v-model:limit="item.pageSize"
        :index="index"
        @pagination="getNumberList"
      />
    </div>
  </ContentWrap>
  <Pagination
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />
  <CustomerForm ref="customerFormRef" @success="getList" />
  <!-- 表单弹窗：添加/修改 -->
  <ReceiveDataForm ref="formRef" @success="getList" />
  <!-- 企业详情 -->
  <EnterpriseDetails ref="companyDetail" @refresh-val="refreshData" />

  <!-- 标签弹窗 -->
  <EditTagForm ref="editTagForm" @success="getList" @setlabel-list="setlabelList" />
</template>
<!-- TODO: 1. 联系号码列表的鼠标经过时，展示添加标记、添加备注的交互组件 -->
<!-- TODO: 2. 获取标签列表api已经开发完毕， 需要对接添加标记时的弹窗 -->
<!-- TODO: 3. 对接放回公海的api /ent/receive-data/delete -->
<!-- TODO: 4. V3.2 对接转客户功能 -->
<!-- TODO: 5. V3.1 对接外呼拨号功能 -->
<!-- TODO: 6. 对接点击企业详情展开详情抽屉的功能 -->
<script setup lang="ts">
import { dateFormatter2 } from '@/utils/formatTime'
import CustomerForm from '../../crm/customer/CustomerForm.vue'
import * as ReceiveDataApi from '@/api/ent/receivedata'
import { getReceiveNumberPage } from '@/api/ent/receivenumber'
import ReceiveDataForm from './ReceiveDataForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import EnterpriseDetails from '../components/EnterpriseDetaill/index.vue'
import EditTagForm from './editTagForm/index.vue'
import { useEntStore } from '@/store/modules/ent'
import AddPending from '@/components/AddPending/index.vue'
import * as seatApi from '@/api/call/seating/index'
import { useSoftPhoneStore } from '@/store/modules/softPhone'
import { usePhoneStore } from '@/store/modules/phone'
import { emitter } from '@/utils/eventBus.ts'

const useSoftPhone = useSoftPhoneStore()
const useStore = usePhoneStore()

defineOptions({ name: 'ReceiveData' })

const entAllCheck = ref(false)

const tablesList = ref([])

const formatDesc = (item, index) => {
  if (item.indexOf(';') != -1) {
    if (index == 2) {
      return item.split(';')[1]
    } else if (index == 1) {
      return item.split(';')[0]
    }
  } else {
    if (index == 2) {
      return 'javascript:void(0)'
    } else if (index == 1) {
      return item
    }
  }
}

const visible1 = ref(false)
/**选择*/
const handleSelectionChange = (val, index) => {
  list.value[index].multipleSelection = val
}
/**全选、反选*/
const handleSelectAll = (val, index) => {
  list.value[index].multipleSelection = val
  list.value[index].checked = val.length != 0
  entAllCheck.value = list.value.every((item) => item.checked)
}
/**单个选择*/
const handleSelect = (val, index) => {
  list.value[index].checked =
    val.length == list.value[index].numberList.filter((item) => item.numberType != 3).length
  entAllCheck.value = list.value.every((item) => item.checked)
}
const companyDetail = ref(null)

const selectable = (row) => {
  return row.numberType != 3
}

const getTables = (el, index) => {
  if (el) {
    tablesList.value[index] = el
  }
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const isLoading = ref(false)
/**批量添加到待拨打*/
const addCall = async () => {
  try {
    isLoading.value = true
    const arr = []
    const arr2 = list.value.filter((item) => item.multipleSelection.length)

    arr2.map((item) => {
      item.multipleSelection.map((init) => {
        const exists = arr.some((i) => i.number == init.number)
        if (!exists) {
          arr.push({
            name: item.entName,
            number: init.number,
            source: 'ent',
            sourceId: item.entId
          })
        }
      })
    })
    const data = await seatApi.batchCreateList({ list: arr })
    emitter.emit('add_pending')
    ElMessage.success(`已自动去重,成功添加${arr.length}个待拨打!`)
  } finally {
    isLoading.value = false
  }
}
/**企业列表详细*/
const getNumberList = async (param) => {
  try {
    if (param) {
      list.value[param.index].pageNo = param.page
      list.value[param.index].pageSize = param.limit
      const params = {
        pageNo: param.page,
        pageSize: param.limit,
        entId: list.value[param.index].entId
      }
      const data = await getReceiveNumberPage(params)
      list.value[param.index].numberList = data.list
      list.value[param.index].total = data.total
      list.value[param.index].checked = false
      entAllCheck.value = list.value.every((item) => item.checked)
    }
  } catch {}
}

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  entName: undefined,
  followStatus: undefined,
  lastFollowRecord: undefined,
  lastFollowTime: [],
  lastFollowType: undefined,
  tags: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

/**全选全不选*/
const setALL = () => {
  list.value.forEach((item, index) => {
    if (item.numberList.length != 0) {
      const leng = item.numberList.filter((item) => item.number && item.numberType != 3)
      if (item.checked && entAllCheck.value) {
      } else if (!item.checked && !entAllCheck.value) {
      } else if (
        !item.checked &&
        tablesList.value[index].getSelectionRows().length == leng.length
      ) {
        item.checked = entAllCheck.value
      } else {
        item.checked = entAllCheck.value
        tablesList.value[index].toggleAllSelection()
      }
    } else {
      item.checked = entAllCheck.value
    }
  })
}
/**选择首条*/
const changeListOne = () => {
  list.value.forEach((item, index) => {
    if (item.numberList.length != 0) {
      const idx = item.numberList.findIndex((item) => item.number && item.number != '')
      tablesList.value[index].toggleRowSelection(item.numberList[idx])
    } else {
      item.checked = entAllCheck.value
    }
  })
}
/**批量添加到待拨打*/
const isAllEmpty = computed(() => {
  return list.value.every((item) => item.multipleSelection.length === 0)
})
/**批量放入公海checked*/
const isAllPool = computed(() => {
  return list.value.every((item) => !item.checked)
})
/**单个操作*/
const setALLNo = (index) => {
  entAllCheck.value = list.value.every((item) => item.checked)
  if (tablesList.value[index].data.length != 0) {
    if (list.value[index].checked) {
      tablesList.value[index].toggleAllSelection()
    } else {
      tablesList.value[index].toggleAllSelection()
    }
  }
}
/**放入公海*/
const addPool = async () => {
  try {
    await message.delConfirm('确定将所选数据放入公海吗?')
    const arr = list.value.filter((item) => item.checked)
    const data = arr.map((item) => item.id)
    await ReceiveDataApi.deleteBatchData(data)
    ElMessage.success('操作成功')
    getList()
  } catch {}
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  entAllCheck.value = false
  try {
    const data = await ReceiveDataApi.getReceiveDataPage(queryParams)

    // 使用 Promise.all 并行获取号码列表
    const numberListPromises = data.list.map(async (element, index) => {
      element.checked = false
      element.numberList = []
      element.pageNo = 1
      element.pageSize = 10
      element.total = 0
      element.multipleSelection = []
      element.expersion = index === 0 // 只有第一条默认展开
      element.loading = false // 为每个企业添加独立的 loading 状态

      // 如果当前企业是展开状态，才加载号码列表
      element.loading = true
      const params = {
        pageNo: element.pageNo,
        pageSize: element.pageSize,
        entId: element.entId
      }
      const res = await getReceiveNumberPage(params)
      element.numberList = res.list
      element.total = res.total
      element.loading = false

      return element
    })

    // 等待所有企业数据初始化完成
    const processedList = await Promise.all(numberListPromises)
    list.value = processedList
    total.value = data.total
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const customerFormRef = ref()
const openCustomerForm = (row) => {
  customerFormRef.value.openByEnt(row.entId, row.number)
}
/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, data: any, id?: number) => {
  formRef.value.open(type, data, id)
}

/** 删除按钮操作 放回公海 */
const putBackSea = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReceiveDataApi.deleteReceiveData(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 跟进状态枚举
const followStatusMap = {
  false: { type: 'warning', value: '未跟进' },
  true: { type: 'primary', value: '已跟进' }
}
/*展开收起*/
const setToggleUp = (index, value) => {
  list.value[index].expersion = value
}
// 打电话
const onCall = (row, callee, item) => {
  emitter.emit('simCall', {
    callee,
    source: 'ent',
    sourceId: row.entId
  })
  onEntNameClick(item)
  emitter.emit('userCallCallee', callee)
}
const setlabelList = (value) => {
  queryParams.labelList = value
}
const editTagForm = ref(null)
/*编辑标签*/
const openTagForm = (type: string, id?: number, tag?: Array) => {
  editTagForm.value.open(type, id, tag)
}

/** 初始化 **/
onMounted(() => {
  getList()
})
// 企业详情
const onEntNameClick = (item, val, index) => {
  //                            显示             cid        锚点?  下标
  companyDetail.value.setDrawer(true, item.entId, val, index)
}
// 企业详情更新 刷新数据
const refreshData = () => {}
</script>
<style scoped>
.disnone {
  display: none;
}
</style>
